package igloo.ui;

import igloo.aws.Region;
import igloo.model.Igloo;
import igloo.model.IglooAdapter;
import igloo.model.Vault;

import javax.swing.table.AbstractTableModel;

public class VaultTableModel extends AbstractTableModel
{
    private static final long serialVersionUID = 1L;

    private Igloo mIgloo;
    private Region mRegion;

    private final IglooListener mListener = new IglooListener();

    public VaultTableModel()
    {
    }

    public VaultTableModel(Igloo igloo, Region region)
    {
        setIgloo(igloo);
        setRegion(region);
    }

    public Igloo getIgloo()
    {
        return mIgloo;
    }

    public void setIgloo(Igloo igloo)
    {
        if(mIgloo != null)
            mIgloo.removeListener(mListener);

        mIgloo = igloo;

        if(mIgloo != null)
            mIgloo.addListener(mListener);
    }

    public Region getRegion()
    {
        return mRegion;
    }

    public void setRegion(Region region)
    {
        mRegion = region;
    }

    @Override
    public int getRowCount()
    {
        int rowCount = 0;
        if(mIgloo != null)
            rowCount = mIgloo.getVaults(mRegion).size();

        return rowCount;
    }

    @Override
    public int getColumnCount()
    {
        return 1;
    }

    @Override
    public String getColumnName(int columnIndex)
    {
        if(columnIndex == 0)
            return "Vault";

        return "UNKNOWN";
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex)
    {
        return mIgloo.getVaults(mRegion).get(rowIndex).getName();
    }

    public Vault getVaultAt(int rowIndex)
    {
        return mIgloo.getVaults(mRegion).get(rowIndex);
    }

    private class IglooListener extends IglooAdapter
    {
        @Override
        public void vaultAdded(Vault vault)
        {
            fireTableDataChanged();
        }

        @Override
        public void vaultRemoved(Vault vault)
        {
            fireTableDataChanged();
        }
    }
}
